
import React, { Fragment, useState, useRef, useEffect } from 'react';
import { Tag, Icon, Input } from 'antd';

// value: []
const TagList = ({
    value = [],
    onChange,
    addButtonName = 'New Tag',
    disabled,
    keyLength = 10
}) => {
    const [inputVisible, setInputVisible] = useState(false);
    const [inputValue, setInputValue] = useState('');
    const input = useRef(null);
    const handleClose = (item, e) => {
        e.preventDefault();
        const findIndex = value.findIndex(
            val => val.key === item.key && val.value === item.value
        );

        onChange([...value.slice(0, findIndex), ...value.slice(findIndex + 1)]);
    };
    const handleInputConfirm = () => {
        if (inputValue && value.indexOf(inputValue) === -1) {
            onChange([
                ...value,
                {
                    key: '',
                    value: inputValue
                }
            ]);
        }
        setInputVisible(false);
        setInputValue('');
    };
    useEffect(() => {
        if (inputVisible) {
            input.current.focus();
        }
    }, [inputVisible]);
    return (
        <Fragment>
            {Array.isArray(value) &&
                value.map(item => {
                    const isLongTag = item.value.length > 20;
                    return (<Tag
                        key={item.key}
                        closable={!disabled}
                        onClose={e => handleClose(item, e)}
                    >
                        {isLongTag ? `${item.value.slice(0, 20)}...` : item.value}
                    </Tag>)
                })}
            {inputVisible && (
                <Input
                    ref={input}
                    type="text"
                    size="small"
                    style={{ width: '20em' }}
                    value={inputValue}
                    onChange={e => setInputValue(e.target.value)}
                    onBlur={handleInputConfirm}
                    onPressEnter={handleInputConfirm}
                />
            )}
            {!inputVisible && !disabled && value.length < keyLength && (
                <Tag
                    onClick={() => { if (disabled) { return; }setInputVisible(true) }}
                    style={{ background: '#fff', borderStyle: 'dashed' }}
                >
                    <Icon type="plus" /> {addButtonName}
                </Tag>
            )}
        </Fragment>
    );
};

export default TagList;
